//
//  PostModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/23/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit


struct PostModel {
    
    struct Tag {
        var text: String
        var color: UIColor
    }
    
    var post: Post!
    
    init (post: Post) {
        self.post = post
    }
    
    var marka: String {
        return post.car.marka?.name_ru ?? ""
    }
    
    var model: String {
        return post.car.model?.name_ru ?? ""
    }
    
    var pokolenie: String {
        return post.car.generation?.name ?? ""
    }
    
    var modification: String {
        return post.car.modification?.name ?? ""
    }
    
    var serie: String {
        return post.car.serie?.name ?? ""
    }
    
    var price: String {
        let s = String(post.price)
        let index = s.index(s.startIndex, offsetBy: s.count % 3)
        let sPart = s[index...]
        let priceText = s[..<index] + " " + String(sPart.enumerated().map { $0 > 0 && $0 % 3 == 0 ? [" ", $1] : [$1]}.joined())
        return priceText.trimmingCharacters(in: .whitespacesAndNewlines) + " ₸"
    }
    
    var date: String {
        if let timestamp = post.timestamp {
            let formatterDate = FormatterDate()
            if let postDate = formatterDate.getDate(inputDate: timestamp) {
                
                let _date = formatterDate.findDifference (date: postDate)
                return _date
                
            } else {
                return ""
            }
        } else {
            return ""
        }
    }
    
    var leftDaysText: String {
        let formatterData = FormatterDate()
        
        if let timestamp = post.timestamp {
            if let date = formatterData.getDate(inputDate: timestamp) {
                return formatterData.getLeftDays(timestamp: Int(date.timeIntervalSince1970), maxDays: 60)
            } else {
                return "Неизвестно"
            }
        } else {
            return "Неизвестно"
        }
    }
    
    
    var visCount: String {
        return String(post.visCount)
    }
    
    var isLiked: Bool {
        return post.isLiked
    }
    
    var region: City? {
        return post.city
    }
    
    var images: [PostImage] {
        return post.images ?? []
    }
    
    var localImages: [UIImage] {
        return post.localImgs ?? []
    }
    
    var isNew: Bool {
        return post.isNew
    }
    
    var tag: Tag? {
        return post.isSrochno || post.isNew ? Tag(text: post.isSrochno ? "Срочно" : "Новый", color: post.isSrochno ? .rgb(255, 111, 41) : .rgb(87, 172, 87)) : nil
    }
    
    var isTop: Bool {
        return post.isTop
    }
    
    var isRassrochka: Bool {
        return post.isRassrochka
    }
    
    var postMarketing: PostReklama {
        return PostReklama(isTop: post.isTop, searchUp: post.isSearchUp, special: post.isSpecial, colored: post.isColored)
    }
}
